package com.yang.test.controller;

import com.yang.test.domain.DTO.ResultDTO;
import com.yang.test.domain.VO.ResultHVO;
import com.yang.test.domain.QuestionH;
import com.yang.test.domain.Result;
import com.yang.test.service.HldzyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api")
public class HldzyController {
    
    @Autowired
    private HldzyService hldzyService;
    
    /**
     * 获取所有测试题目
     */
    @GetMapping("/questionsH")
    public Result<?> getAllQuestions() {
        Instant start = Instant.now();
        log.info("开始获取所有题目");
        
        try {
            List<QuestionH> questions = hldzyService.getAllQuestions();
            Collections.shuffle(questions); // 随机排序问题
            
            log.info("获取题目完成, 题目数量: {}, 总耗时: {}", 
                    questions.size(), Duration.between(start, Instant.now()));
            
            return Result.success(questions);
        } catch (Exception e) {
            log.error("获取题目失败: {}", e.getMessage(), e);
            return Result.error("获取题目失败: " + e.getMessage());
        }
    }
    
    /**
     * 提交测试结果并获取分析
     */
    @PostMapping("/results")
    public Result<?> submitResult(@RequestBody ResultDTO request) {
        Instant start = Instant.now();
        log.info("开始处理结果提交请求");
        
        try {
            ResultHVO result = hldzyService.calculateResult(request.getAnswers());
            
            log.info("结果计算完成, 总耗时: {}", Duration.between(start, Instant.now()));
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("处理结果提交请求失败: {}", e.getMessage(), e);
            return Result.error("处理请求失败: " + e.getMessage());
        }
    }
}